package com.yulongtian.oneProblemEveryDay.month202302;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * https://leetcode.cn/problems/merge-similar-items/
 *
 * @author yulongTian
 * @create 2023-02-28 9:30
 */
public class Test23 {
    public static void main(String[] args) {
        int[][] items2 = {{1, 1}, {4, 5}};
        int[][] items1 = {{3,1},{1,5}};
        System.out.println(new Test23().mergeSimilarItems(items1, items2));
    }

    public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
        int p1 = 0, p2 = 0;
        int n1 = items1.length;
        int n2 = items2.length;
        List<List<Integer>> ans = new ArrayList<>();

        Arrays.sort(items1, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        Arrays.sort(items2, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        while (p1 < n1 && p2 < n2) {
            if (items1[p1][0] == items2[p2][0]) {
                List<Integer> temp = new ArrayList<>(2);
                temp.add(items1[p1][0]);
                temp.add(items2[p2][1] + items1[p1][1]);
                ans.add(temp);
                p1++;
                p2++;
            } else if (items1[p1][0] < items2[p2][0]) {
                List<Integer> temp = new ArrayList<>(2);
                temp.add(items1[p1][0]);
                temp.add(items1[p1][1]);
                ans.add(temp);
                p1++;
            } else {
                List<Integer> temp = new ArrayList<>(2);
                temp.add(items2[p2][0]);
                temp.add(items2[p2][1]);
                ans.add(temp);
                p2++;
            }
        }
        if (p1 == n1 && p2 == n2) {
            return ans;
        }
        if (p1 == n1) {
            for (int i = p2; i < n2; i++) {
                List<Integer> temp = new ArrayList<>(2);
                temp.add(items2[i][0]);
                temp.add(items2[i][1]);
                ans.add(temp);
            }
        }
        if (p1 != n1 && p2 == n2) {
            for (int i = p1; i < n1; i++) {
                List<Integer> temp = new ArrayList<>(2);
                temp.add(items1[i][0]);
                temp.add(items1[i][1]);
                ans.add(temp);
            }
        }
        return ans;
    }
}
